package com.gy.smart.life;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.gy.smart.MyApplication;
import com.gy.smart.R;
import com.gy.smart.base.BaseBean;
import com.gy.smart.base.BaseFragment;
import com.gy.smart.life.adapter.ADAdapter;
import com.gy.smart.life.adapter.LifeHomeTypeAdapter;
import com.gy.smart.life.bean.LifeHomeBean;
import com.gy.smart.life.bean.LifeListBean;
import com.gy.smart.life.bean.LifeTypeBean;
import com.gy.smart.life.view.LifeHomeMapMarkerView;
import com.gy.smart.util.AnimUtil;
import com.gy.smart.util.ListViewItemListener;
import com.gy.smart.util.LocationManagers;
import com.gy.smart.util.RequestResultListener;
import com.gy.smart.util.Urls;
import com.gy.smart.util.map.MapBaseDrawable;
import com.gy.smart.view.PageIndicatorView;

import org.xutils.http.RequestParams;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 高岳 on 2016/12/25.
 * Describe:生活首页
 */
public class LifeFragment extends BaseFragment implements ListViewItemListener,LocationManagers.LocationChange,AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener,
        AMap.OnMarkerClickListener {

    private final int UPDATE_TIME = 5000;
    private View _rootView;
    private ViewPager adViewPager;
    private PageIndicatorView indicatorView;
    private GridView gridView;
    private MapView mapView;
    private LifeHomeTypeAdapter typeAdapter;
    private ADAdapter adAdapter;
    private ArrayList<String> adList,adRequest;
    private List<LifeTypeBean> typeLists;
    private boolean isAdd = true;
    private AMap aMap;
    private LatLng center;//地图中心点
    private double endLat, endLong;
    private AMapLocation aMapLocation;//定位位置信息
    private LifeHomeBean bean;
    private MapBaseDrawable mMapBaseDrawable;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);
        if (_rootView == null) {
            _rootView = View.inflate(getActivity(), R.layout.fragment_life, null);
            mapView = (MapView) _rootView.findViewById(R.id.fg_life_home_mapview);
            mapView.onCreate(savedInstanceState);
            aMap = mapView.getMap();
            initViews();
            initDatas();
            setListeners();
            fillDatas();
        }
        return _rootView;
    }

    @Override
    protected View setView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_life,null);
        return view;
    }

    @Override
    protected void initView() {}
    protected void initData() {}
    private void initViews(){
        adViewPager = (ViewPager) _rootView.findViewById(R.id.fg_life_ad_viewpager);
        indicatorView = (PageIndicatorView) _rootView.findViewById(R.id.fg_life_ad_pagepoint);
        gridView = (GridView) _rootView.findViewById(R.id.fg_life_gridview);

    }

    private void initDatas(){
        adList = new ArrayList<>();
        adRequest = new ArrayList<>();
        typeLists = new ArrayList<>();
        typeAdapter = new LifeHomeTypeAdapter(mContext,typeLists);
        mMapBaseDrawable = new LifeHomeMapMarkerView(mContext);
        center = new LatLng(MyApplication.aMapLocation.getLatitude(), MyApplication.aMapLocation.getLongitude());

        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);//设置地图缩放按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//设置地图zoom级别
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(center));
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
    }

    protected void setListeners() {
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext,LifeMapActivity.class);
                intent.putExtra("titles", (Serializable) bean.lifeCategoryList);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
            }
        });
    }

    protected void fillDatas() {
//        setViewPager();
        gridView.setAdapter(typeAdapter);
        if(MyApplication.aMapLocation != null){
            this.aMapLocation = MyApplication.aMapLocation;
            getData();
        }
    }

    /** 设置广告*/
    private void setViewPager() {
        indicatorView.setPropertise(adRequest.size(), 0);
        adAdapter = new ADAdapter(mContext,adList);
        adAdapter.setListener(this);
        adViewPager.setAdapter(adAdapter);
        adViewPager.setCurrentItem(adRequest.size() * 100);
        adViewPager.invalidate();
        if(adList.size() > 1){
            adSwitchHandler.postDelayed(adSwitchRunnable, UPDATE_TIME);
        }

        adViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                if(adRequest.size() > 1){
                    indicatorView.setCurrentPosition(arg0 % adRequest.size());
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (arg0 == 1) {
                    adSwitchHandler.removeCallbacks(adSwitchRunnable);
                } else {
                    adSwitchHandler.removeCallbacks(adSwitchRunnable);
                    adSwitchHandler.postDelayed(adSwitchRunnable, UPDATE_TIME);
                }
            }
        });
    }

    @Override
    public void doPassActionListener(Object obj, int org1, int org2, String str) {
        Intent intent = new Intent(mContext,LifeDetailActivity.class);
        intent.putExtra("life_id",bean.lifeSlideList.get(org2 % 3).life_id);
        startActivity(intent);
        AnimUtil.pushLeftInAndOut(getActivity());
    }

    /**  获取生活数据*/
    private void getData(){
        showLoadDialog(1);
        RequestParams params = new RequestParams(Urls.url_life_home);
        params.addParameter("longitude",aMapLocation.getLongitude()+"");
        params.addParameter("latitude",aMapLocation.getLatitude()+"");
        postRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                if(result.status == 1){
                    bean = gson.fromJson(result.data,LifeHomeBean.class);
                    if(bean.lifeSlideList != null){
                        for(LifeHomeBean.LifeSlideListBean slideListBean : bean.lifeSlideList){
                            adList.add(slideListBean.slide_img_url);
                        }
                        setViewPager();
                    }
                    if(bean.lifeCategoryList != null){
                        typeLists.addAll(bean.lifeCategoryList);
                        typeAdapter.notifyDataSetChanged();
                    }

                    if(bean.lifeData != null){
                        for(LifeListBean lifeListBean : bean.lifeData){
                            aMap.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(lifeListBean.latitude),
                                    Double.valueOf(lifeListBean.longitude)))
                                    .icon(BitmapDescriptorFactory.fromBitmap(mMapBaseDrawable.createMarker(lifeListBean)))
                                    .draggable(true));
                        }
                    }

                }
                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }
        });
    }


    @Override
    public void locationChange() {
        this.aMapLocation = MyApplication.aMapLocation;
        getData();
    }

    /**
     * 更换广告页
     */
    private Handler adSwitchHandler = new Handler();
    /**
     * 更换广告页的runnable
     */
    private Runnable adSwitchRunnable = new Runnable() {

        @Override
        public void run() {

            if (null != adViewPager && null != adList && adList.size() > 0) {
                int nextPosition;
                int currentItem = adViewPager.getCurrentItem();
                if (isAdd) {
                    if (currentItem == adList.size() - 1) {
                        nextPosition = currentItem - 1;
                        isAdd = false;
                    } else {
                        nextPosition = ++currentItem;
                    }
                } else {
                    if (currentItem == 0) {
                        nextPosition = currentItem + 1;
                        isAdd = true;
                    } else {
                        nextPosition = --currentItem;
                    }
                }
                adViewPager.setCurrentItem(nextPosition, true);
            }

            adSwitchHandler.removeCallbacks(adSwitchRunnable);
            adSwitchHandler.postDelayed(adSwitchRunnable, UPDATE_TIME);
        }
    };

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }
}
